# _*_coding:utf-8_*_
import time
from ATS.instrumentDriver import InstCom as inst


def n6075b_setup(dc_inst, grid_peak_list, grid_main_list, drain_list, d_delay, limit, balance):
    # grid_peak_list =  [channel,volt1,limit]  = ['1','-5','0.1']
    # power on CH1/2/3, after 20 seconds, power off
    set_output_state(dc_inst, 1, 0)
    set_output_state(dc_inst, 2, 0)
    set_output_state(dc_inst, 3, 0)

    set_output_volt(dc_inst, grid_peak_list)
    set_output_volt(dc_inst, grid_main_list)
    set_output_volt(dc_inst, drain_list)
    set_output_state(dc_inst, 1)
    set_output_state(dc_inst, 2)
    time.sleep(d_delay)
    set_output_state(dc_inst, 3)
    meas_list = [1, 2, 3]
    print(meas_current(dc_inst, meas_list))
    time.sleep(balance)
    set_output_state(dc_inst, 1, 0)
    set_output_state(dc_inst, 2, 0)
    set_output_state(dc_inst, 3, 0)


def n6075b_poweron(dc_inst, grid_peak_list, grid_main_list, drain_list, d_delay, limit, balance):
    # grid_peak_list =  [channel,volt1,limit]  = ['1','-5','0.1']
    set_output_state(dc_inst, 1, 0)
    set_output_state(dc_inst, 2, 0)
    set_output_state(dc_inst, 3, 0)

    set_output_volt(dc_inst, grid_peak_list)
    set_output_volt(dc_inst, grid_main_list)
    set_output_volt(dc_inst, drain_list)
    set_output_state(dc_inst, 1)
    set_output_state(dc_inst, 2)
    time.sleep(d_delay)
    set_output_state(dc_inst, 3)
    meas_list = [1, 2, 3]
    print('N6705B Power on!')
    print(meas_current(dc_inst, meas_list))


def n6075b_poweroff(dc_inst, d_delay):
    set_output_state(dc_inst, 3, 0)
    time.sleep(d_delay)
    set_output_state(dc_inst, 1, 0)
    set_output_state(dc_inst, 2, 0)
    print('N6705B Power off!')


def set_output_volt(dc_inst, setup_list):
    channel, volt, limit = setup_list
    cmd = "volt %f,(@%s)" % (volt, channel)
    inst.write(dc_inst, cmd)
    if int(channel) == 3:
        cmd = "curr %f,(@%s)" % (limit, channel)
    else:
        cmd = "curr:lim %f,(@%s)" % (limit, channel)
    inst.write(dc_inst, cmd)


def set_output_state(dc_inst, channel, state=1):
    if state:
        cmd = "OUTP 1,(@%s)" % channel
    else:
        cmd = "OUTP 0,(@%s)" % channel
    inst.write(dc_inst, cmd)


def meas_current(dc_inst, channel_list):
    command = generate_command(channel_list)
    cmd = "meas:curr? %s" % command
    inst.write(dc_inst, cmd)
    return inst.read(dc_inst)


def generate_command(channel_list):
    n = len(channel_list)
    if n == 1:
        command = '(@%d)' % channel_list[0]
    elif n > 1:
        command = '(@%d' % channel_list[0]
        for i in range(1, n):
            command = command + "," + str(channel_list[i])
        command = command + ")"
    else:
        print("there is no channel to setup")
        return 0
    return command
